package com.lly.songhigh.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.Gson;
import com.lly.songhigh.R;
import com.lly.songhigh.activity.PlayMusicActivity;
import com.lly.songhigh.adapter.SearchSingleListViewAdapter;
import com.lly.songhigh.constant.StringResouce;
import com.lly.songhigh.constant.URL;
import com.lly.songhigh.entity.MusicInfo;
import com.lly.songhigh.entity.SearchSingle;
import com.lly.songhigh.eventbus.MyEvent;
import com.lly.songhigh.utils.SharedPreferencesUtils;
import com.lly.songhigh.view.SwipeRefreshLoadingLayout;
import com.lly.songhigh.volley.VolleySingleton;

import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;

/**
 * Created by dllo on 15/10/24.
 */
public class SearchSingleSongFragment extends BaseFragment implements AdapterView.OnItemClickListener, SwipeRefreshLoadingLayout.OnLoadListener, SwipeRefreshLoadingLayout.OnRefreshListener {
    private ListView singlesongListView;
    private String startUrl = URL.SEARCHSINGLE;
    private String endUrl;
    private String url;
    private List<SearchSingle.DataEntity> datas;
    private VolleySingleton volleySingleton;
    private List<MusicInfo> musicInfos;
    private int pageCount;
    private int page = 1;

    private SwipeRefreshLoadingLayout refreshLoadingLayout;
    private SearchSingleListViewAdapter searchSingleListViewAdapter;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.search_singlesong, null);
        endUrl = SharedPreferencesUtils.getSharePreStr(getActivity(), "SearchActivityEditText", "endUrl");
        refreshLoadingLayout = (SwipeRefreshLoadingLayout) view.findViewById(R.id.swiperefresh);
        refreshLoadingLayout.setOnLoadListener(this);
        refreshLoadingLayout.setOnRefreshListener(this);
        refreshLoadingLayout.setTopColor(R.color.transparentColor, R.color.transparentColor, R.color.transparentColor, R.color.transparentColor);
        refreshLoadingLayout.setBottomColor(R.color.themeColor, R.color.whiteColor, R.color.themeColor, R.color.whiteColor);
        singlesongListView = (ListView) view.findViewById(R.id.singlesong_listView);
        singlesongListView.setOnItemClickListener(this);
        url = startUrl+ endUrl;
        volleySingleton = VolleySingleton.getInstance();
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initData();
    }

    private void initData() {
        StringRequest request = new StringRequest(url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Gson gson = new Gson();
                SearchSingle searchSingle = gson.fromJson(response, SearchSingle.class);
                datas = searchSingle.getData();
                searchSingleListViewAdapter = new SearchSingleListViewAdapter(getActivity(), datas);
                singlesongListView.setAdapter(searchSingleListViewAdapter);
                pageCount = searchSingle.getPageCount();
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
        volleySingleton.addQueue(request);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        SearchSingle.DataEntity dataEntity = (SearchSingle.DataEntity) parent.getItemAtPosition(position);
        musicInfos = new ArrayList<>();
        if (dataEntity.getUrlList() != null && dataEntity.getUrlList().size() > 0) {
            Intent intent = new Intent(getActivity(), PlayMusicActivity.class);
            for (SearchSingle.DataEntity data : searchSingleListViewAdapter.getDataEntities()) {
                if (data.getUrlList() != null && data.getUrlList().size() > 0) {
                    MusicInfo musicInfo = new MusicInfo();
                    musicInfo.setUrl(data.getUrlList().get(0).getUrl());
                    musicInfo.setDuration(data.getUrlList().get(0).getDuration());
                    musicInfo.setSingerId(data.getSingerId());
                    musicInfo.setSingerName(data.getSingerName());
                    musicInfo.setSongId(data.getSongId());
                    musicInfo.setSongName(data.getName());
                    musicInfo.setAlbum(data.getAlbumName());
                    musicInfo.setResouce(StringResouce.RESOUCE_NET);
                    musicInfos.add(musicInfo);
                }
            }
            intent.putExtra("singerName", dataEntity.getSingerName());
            intent.putExtra("songName", dataEntity.getName());
            intent.putExtra("duration", dataEntity.getUrlList().get(0).getDuration());
            intent.putExtra("resouce", StringResouce.RESOUCE_NET);
            intent.putExtra("singerId", dataEntity.getSingerId());
            intent.putExtra("songId", dataEntity.getSongId());
            EventBus.getDefault().post(new MyEvent.DeliverData(musicInfos, dataEntity.getName()));startActivity(intent);
        } else {
            Toast.makeText(getActivity(), StringResouce.PLAY_ERROR, Toast.LENGTH_LONG).show();

        }
    }

    @Override
    public void onLoad() {
        page ++;
        if (page > pageCount){
            refreshLoadingLayout.setLoading(false);
        }else {
            url = URL.SEARCHSINGLE_LOADSTART + page + URL.SEARCHSINGLE_LOADEND + endUrl;
            StringRequest request = new StringRequest(url, new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    Gson gson = new Gson();
                    SearchSingle searchSingle = gson.fromJson(response, SearchSingle.class);
                    datas = searchSingle.getData();
                    searchSingleListViewAdapter.loadData(datas);
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                }
            });
            volleySingleton.addQueue(request);
            refreshLoadingLayout.setLoading(false);
        }
    }

    @Override
    public void onRefresh() {
        refreshLoadingLayout.setRefreshing(false);
    }
}
